import { Injectable } from '@nestjs/common';
import { FindOneOptions, Repository } from 'typeorm';
import { DeepPartial } from 'typeorm/common/DeepPartial';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';

@Injectable()
export abstract class MySQLBaseService<T> {
  constructor(protected repository: Repository<T>) {}
  async findOne(options: FindOneOptions<T>) {
    return this.repository.findOne(options);
  }
  async findAll() {
    return this.repository.find();
  }
  async create(createDto: DeepPartial<T>) {
    const entity = await this.repository.save(createDto);
    return entity;
  }
  async update(id: number, updateDto: QueryDeepPartialEntity<T>) {
    return this.repository.update(id, updateDto);
  }
  async delete(id: number) {
    return this.repository.delete(id);
  }
  async count() {
    return this.repository.count();
  }
  async findLatest(take: number) {
    const order: any = {
      id: 'DESC',
    };
    return this.repository.find({
      order,
      take,
    });
  }
  async getTrend(tableName: string) {
    const result = await this.repository.query(`
      SELECT DATE_FORMAT(createdAt, '%Y-%m-%d') as date,COUNT(*) as count
      FROM ${tableName}
      GROUP BY date
      ORDER BY date ASC
    `);
    const dates = result.map((row) => row.date);
    const counts = result.map((row) => row.count);
    return { dates, counts };
  }
}
